package com.wn.common.utils

import com.blankj.utilcode.util.EncryptUtils
import com.wn.common.net.config.NET_CONFIG_APP_KEY

/**
 * @Author: wn
 * @Date: 2023/1/11 16:51
 * @Description: 工具函数 文件
 */

/**
 * 把中文转成Unicode码
 */
fun chinaToUnicode(str: String): String {
  val result = StringBuilder()
  for (element in str) {
    // 如果你的Kotlin版本低于1.5，这里 element.code 会报错 找不到方法,请替换成:
    // Kotlin < 1.5
    // var s = Integer.toHexString(element.toInt())
    // Kotlin >= 1.5
    var s = Integer.toHexString(element.code)
    // 英文转16进制后只有两位，补全4位
    if (s.length == 2) s = "00$s"
    result.append("\\u$s")
  }
  return result.toString();
}

/**
 * unicode转中文
 */
fun decodeUnicode(unicode: String): String {
  val builder = StringBuilder()
  val hex = unicode.split("\\\\u".toRegex()).toTypedArray()
  for (i in 1 until hex.size) {
    val data = hex[i].toInt(16)
    builder.append(data.toChar())
  }
  return builder.toString()
}

/**
 * 判断是否为中文字符
 */
fun isChinese(c: Char): Boolean {
  val ub = Character.UnicodeBlock.of(c)
  return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
          || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
          || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
          || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
          || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
          || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
}

/**
 * 解析返回的data数据   TODO 有问题
 */
fun decodeData(data: String?) =
  if (data === null) null else data.let {
    EncryptUtils.decryptBase64AES(
      it.toByteArray(),
      NET_CONFIG_APP_KEY.toByteArray(),
      "AES/CBC/PKCS7Padding",
      "J#y9sJesy*5HmqLq".toByteArray()
    ).toString()
  }